<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="querryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="handleInput"
        />
        <!-- 树形组件 -->
        <!-- heighlight-current: 高亮当前节点 -->
        <!-- node-key: 唯一标识 -->
        <!-- current-change: 节点切换时触发 -->
        <el-tree
          ref="tree"
          node-key="id"
          highlight-current
          :expand-on-click-node="false"
          default-expand-all
          :data="depData"
          :props="defaultProps"
          @current-change="handleCurrentChange"
        >
          <template #default="{ data }">
            <el-row style="width:100%; height:40px;" type="flex" justify="space-between" align="middle">
              <span>{{ data.name }}</span>
            </el-row>
          </template>
        </el-tree>
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'employee:add'" size="mini" type="primary" @click="$router.push('/employee/details')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="头像" width="180">
            <template #default="{ row }">
              <img
                v-if="row.staffPhoto"
                :src="row.staffPhoto"
                alt=""
                style="width: 30px; height: 30px; border-radius: 50%;"
              >
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="180" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              <span>{{ row.formOfEmployment === 1 ? '正式' : '非正式' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column prop="mobile" label="操作">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/details/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="editRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定要删除该员工吗？"
                @onConfirm="delEmp(row)"
              >
                <el-button slot="reference" size="mini" type="text" style="margin-left:10px">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="height:60px;">
          <el-pagination layout="total,prev,pager,next" :total="total" @current-change="changePage" />
        </el-row>
      </div>
    </div>
    <!-- excel导入弹层 -->
    <import-excel :show-excel-dialog.sync="showExcelDialog" />
    <!-- 分配角色弹层 -->
    <el-dialog title="分配角色" :visible.sync="shwoRoleDialog" @close="close">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row type="flex" justify="center" style="margin-top:50px;">
        <el-button type="primary" size="mini" @click="submitRole">确认</el-button>
        <el-button size="mini" @click="close">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepData } from '@/api/department'
import { assignPermissions, delEmployee, exportEmployee, getEmployeeDetail, getEmployeeList, getRoleList } from '@/api/employee'
import { transListToTree } from '@/utils'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      depData: [
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 传递的员工查询参数
      querryParams: {
        departmentId: null, // 部门id
        page: 1, // 当前页码
        pagesize: 10, // 每页条数
        keyword: '' // 根据名字模糊查询
      },
      tableData: [],
      total: 0,
      timer: null,
      showExcelDialog: false,
      shwoRoleDialog: false,
      roleIds: [], // 选中的角色列表
      roleList: [], // 所有角色列表
      currentRoleId: null // 当前角色id
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 获取树状数据
    async getData() {
      const res = await getDepData()
      this.depData = transListToTree(res, 0)
      // console.log(this.depData)
      // 获取默认部门id，即数据中第一项id
      this.querryParams.departmentId = this.depData[0].id
      // 一进入页面默认选中第一项
      // vue渲染是异步的，需要等tree组件渲染完成，再调用方法选中高亮
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.querryParams.departmentId)
      })
      this.getList()
    },
    // 获取员工列表
    async getList() {
      const data = await getEmployeeList(this.querryParams)
      // console.log(data)
      this.tableData = data.rows
      this.total = data.total
    },
    // 点击时切换Id并获取列表数据,默认显示第一页
    handleCurrentChange(currentNode) {
      // 点击树形组件获取当前节点数据，两个参数，一个为当前节点数据一个为节点的node对象
      this.querryParams.departmentId = currentNode.id // 点击节点切换id
      this.querryParams.page = 1 // 默认为第一页内容，防止无内容
      // 获取员工列表
      this.getList()
    },
    // 切换页码
    changePage(newPage) {
      this.querryParams.page = newPage // 切换页码
      this.getList() // 获取员工列表
    },
    // 输入框输入时触发（防抖）
    handleInput() {
      clearTimeout(this.timer)
      this.timer = setTimeout(async() => {
        // 等一等再发送请求
        this.querryParams.page = 1 // 默认显示第一页
        // 此次请求的id，已经在list中选中，为当前选中部门的id
        await this.getList()
      }, 1000)
    },
    // 导出员工excel
    async exportExcel() {
      const res = await exportEmployee()
      console.log(res)
      FileSaver.saveAs(res, '员工列表.xlsx')
    },
    // 删除员工 todo
    async delEmp(row) {
      // 1. 调用删除接口
      await delEmployee(row.id)
      // 2. 提示信息
      this.$message.success('删除员工成功')
      // 3. 重新获取员工列表
      this.getList()
      // 4. 如果删除的是最后一页的最后一条数据，那么就返回上一页
      if (this.tableData.length === 1 && this.querryParams.page > 1) {
        this.querryParams.page--
      }
    },
    // 编辑员工角色
    async editRole(id) {
      // 获取所有角色
      const res = await getRoleList()
      // 获取当前员工角色，存储一下id，方便后续使用
      this.currentRoleId = id
      const list = await getEmployeeDetail(id)
      // 赋值给对应的数组
      this.roleList = res
      this.roleIds = list.roleIds
      // 显示弹层，注意要等请求发送完毕再显示弹层，不然会出现数据延迟回显bug
      this.shwoRoleDialog = true
    },
    // 关闭角色弹层
    close() {
      this.shwoRoleDialog = false
      this.checkList = []
    },
    // 确认编辑
    async submitRole() {
      await assignPermissions({
        id: this.currentRoleId,
        roleIds: this.roleIds
      })
      this.$message.success('编辑成功')
      this.close()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
